import { WeApp } from '../../../common/common';
import { config } from '../../../etc/config';
import * as __ from '../../../assets/plugins/underscore.js';
import httpClient from '../../../common/http-client';
import { OrderListItem, OrderDetail } from '../../../model/order';
import { IApiResult, PageData } from '../../../model/page-date';
import wxService from '../../../common/wxService'
import tools from '../../../common/tools'
import { MlcEnum } from '../../../model/enum'
import { ISubmitOrderResult } from '../../../model/order';
import utils from '../../../utils/utils';
import { prompt, countDown } from '../../../assets/components/wux';
import orderHelper from '../../../utils/orderHelper';

const app = getApp();
interface OrderListPageData {
    currentStatus?: number,
    currentTab?: number,
    navList: Array<INavItem>,
    orders?: PageData<OrderListItem>,
    hasRefesh: boolean,
    btnDisabled?: boolean,
    times?: {},
    invoiceId?: string,
    orderStatus: Array<string>
}

interface INavItem {
    name: string,
    status?: number
}

interface OrderListPage extends IPage {

}

class OrderListPage {
    private prompt;
    private i: number = 0;
    private status: number;
    private invoiceId: string;
    private self = this;
    navList: Array<INavItem> = [
        { name: '全部', status: null },
        { name: '待付款', status: MlcEnum.OrderStauts.待付款 },
        { name: '待发货', status: MlcEnum.OrderStauts.待发货 },
        { name: '已完成', status: MlcEnum.OrderStauts.已完成 },
        { name: '已取消', status: MlcEnum.OrderStauts.已取消 }
    ]

    getNavStatusIndex = (status) => {
        let index: number = 0;
        __.find(this.navList,
            function (item, key: number) {
                if (item.status === status) {
                    index = key;
                    return false;
                }
            }
        );
        return index;
    }

    emptyOrders: PageData<OrderListItem> = {
        hasNext: true,
        datas: []
    }

    public data: OrderListPageData = {
        currentStatus: -1,
        currentTab: 0,
        navList: this.navList,
        orders: this.emptyOrders,
        hasRefesh: true,
        orderStatus: MlcEnum.toArray('OrderStauts')
    }

    public onLoad(options): void {
        if (options.invoiceId) {
            this.invoiceId = options.invoiceId;
            this.setData({ 'invoiceId': this.invoiceId });
        } else {
            if (options.status || options.status === '0') {
                this.status = Math.abs(options.status);
                this.setData({
                    'currentTab': this.getNavStatusIndex(this.status)
                })
            }
        }
        this.getOrders();
    }

    swichNav(e) {
        var cur = e.target.dataset.current;
        if (this.data.currentTab == cur) {
            return false;
        }
        else {
            this.setData({
                currentTab: cur,
                orders: this.emptyOrders
            })
        }
        this.checkCor();
    }

    checkCor() {
        if (this.data.currentTab > 2) {
            this.setData({
                scrollLeft: 150
            })
        } else {
            this.setData({
                scrollLeft: 0
            })
        }
        this.i = 0;
        this.status = this.navList[this.data.currentTab].status
        if (this.prompt) {
            this.prompt.hide();
        }
        this.getOrders();
    }

    getOrders() {
        wxService.showLoading();
        this.i += 1;
        httpClient.get<OrderListItem>(tools.buildUrl(config.order.order_list, { i: this.i, status: this.status, invoiceId: this.invoiceId }))
            .then((res) => {
                wx.hideLoading();
                wx.stopPullDownRefresh();
                if (res.succeed) {
                    let d = this.data.orders;
                    let times = this.data.times;
                    const startIndex = d.datas.length;
                    if (this.i == 1) {
                        d = res.pageData;
                        times = {};
                    } else {
                        d.datas = d.datas.concat(res.pageData.datas);
                        d.hasNext = res.pageData.hasNext;
                    }
                    __.find(res.pageData.datas, (item: OrderListItem, index) => {
                        item.isImgsArry = __.isArray(item.goodsImgs);
                        if (startIndex == 0) {
                            item["index"] = startIndex + index;
                        } else {
                            item["index"] = startIndex + (index == 0 ? (index + 1) : index);
                        }
                        if (item.status == MlcEnum.OrderStauts.待付款) {
                            new countDown({
                                //item.expire
                                date: new Date(item.expire),
                                render(date) {
                                    const hours = this.leadingZeros(date.hours, 2) + ' 时 '
                                    const min = this.leadingZeros(date.min, 2) + ' 分 '
                                    const sec = this.leadingZeros(date.sec, 2) + ' 秒 '
                                    const d = {}
                                    times[item.id] = hours + min + sec;
                                    this.setData({
                                        'times': times
                                    })
                                },
                                onEnd: () => {
                                    let sd = {};
                                    delete times[item.id];
                                    item.status = MlcEnum.OrderStauts.已过期;
                                    if (this.status == MlcEnum.OrderStauts.待付款) {
                                        this.data.orders.datas.splice(item['index'], 1);
                                        sd[`orders.datas`] = this.data.orders.datas;
                                    } else {
                                        sd[`orders.datas[${item['index']}]`] = item;
                                    }
                                    sd['times'] = times
                                    this.setData(sd);
                                    setTimeout(() => {
                                        this.checkDatasCount()
                                    }, 1);
                                }
                            })
                        }
                    })

                    let sData = { 'orders': d };
                    sData["hasRefesh"] = false;
                    this.setData(sData)
                    this.checkDatasCount();
                }
                else {
                    wxService.showToast(res.msg);
                }
            })
    }


    public toAgain(e) {
        wxService.showLoading();
        const id = e.currentTarget.dataset.id;
        wx.setStorageSync(config.storageNames.cart_order_id, id);
        wxService.switchTab('/pages/cart/list/index');
    }

    public toPay(e) {
        if (this.data.btnDisabled) {
            return;
        }
        utils.setBtnStatus(this);
        const id = e.currentTarget.dataset.id;
        orderHelper.Pay(id).then(res => {
            utils.setBtnStatus(this);
        })

        // httpClient.post<ISubmitOrderResult>(config.order.order_pay_apply_wx, { ids: [id] })
        //     .then(res => {
        //         wx.hideLoading();
        //         utils.setBtnStatus(this);
        //         if (res.succeed) {
        //             res.value.orderId = id;
        //             utils.orderPayment(res.value, (pres) => {
        //                 utils.showToastText('支付已取消');
        //             });
        //         } else {
        //             wxService.showToast(res.msg);
        //         }
        //     }).catch(e => {
        //         utils.setBtnStatus(this);
        //     });
    }

    public toCancle(e) {
        if (this.data.btnDisabled) {
            return;
        }
        utils.setBtnStatus(this)
        const target = e.currentTarget.dataset;
        wxService.showModal({ content: '是否取消该订单？', confirmColor: '#1972ff' })
            .then((res: wx.ShowModalResult) => {
                utils.setBtnStatus(this)
                if (res.confirm) {
                    wxService.showLoading();
                    utils.setBtnStatus(this)
                    httpClient.post(config.order.order_cancle, { id: target.id })
                        .then(res => {
                            wx.hideLoading();
                            utils.setBtnStatus(this)
                            if (res.succeed) {
                                const datas: any = this.data.orders.datas;
                                datas[target.index].status = MlcEnum.OrderStauts.已取消;
                                datas.shift(target.index, 1);
                                this.setData({
                                    'orders.datas': datas
                                });
                                this.checkDatasCount();
                            } else {
                                wxService.showToast(res.msg);
                            }
                        });
                }
            }).catch(e => {
                utils.setBtnStatus(this);
            })
    }

    toReceived(e) {
        if (this.data.btnDisabled) {
            return;
        }
        utils.setBtnStatus(this)
        const target = e.currentTarget.dataset;
        wxService.showModal({ content: '是否确认收货？', confirmColor: '#1972ff' })
            .then((res: wx.ShowModalResult) => {
                utils.setBtnStatus(this)
                if (res.confirm) {
                    wx.hideLoading();
                    utils.setBtnStatus(this)
                    httpClient.post(config.order.logistics_sign, { id: target.logisticsId })
                        .then(res => {
                            utils.setBtnStatus(this)
                            if (res.succeed) {
                                const datas: any = this.data.orders.datas;
                                datas.shift(target.index, 1);
                                this.setData({
                                    'orders.datas': datas
                                });
                                this.checkDatasCount();
                            } else {
                                wxService.showToast(res.msg);
                            }
                        })
                }
            }).catch(e => {
                utils.setBtnStatus(this);
            })
    }

    onReachBottom() {
        if (!this.data.orders.hasNext || this.data.hasRefesh) {
            return;
        }
        this.setData({
            'hasRefesh': true,
        });
        this.status = this.navList[this.data.currentTab].status;
        this.getOrders();
    }

    onPullDownRefresh() {
        this.i = 0;
        this.status = this.navList[this.data.currentTab].status;
        this.getOrders();
    }

    checkDatasCount() {
        const datas = this.data.orders.datas;
        this.prompt = prompt.init('msg1', {
            title: '',
            text: `您没有${MlcEnum.OrderStauts[this.status] || ''}相关订单!`,
            icon: 'http://r.59im.com/wx/tips/lack_without_order_icon@2x.png'
        });
        if (!datas || datas.length == 0) {
            setTimeout(() => {
                this.prompt.show();
            }, 400);
        }
        else {
            this.prompt.hide();
        }
    }
    // showActionSheet(e) {
    //     const target = e.currentTarget.dataset;
    //     wxService.showActionSheet({ itemList: ['再来一单', '联系平台'], itemColor: '#1724ff' })
    //         .then((res: wx.ShowActionSheetResult) => {
    //             if (res.tapIndex == 0) {
    //                 wx.setStorageSync(config.storageNames.cart_order_id, target.id);
    //                 wxService.switchTab('/pages/cart/list/index');
    //             } else if (res.tapIndex == 1) {

    //             }
    //         })
    // }

}
Page(new OrderListPage());
